package com.vogue.supplymall.order.common;

import javafx.util.Pair;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * The type Transfrom to map utils.
 *
 * @aouthor: zhangliang
 * @date: Create in 2018-02-07
 */
public class TransformToMapUtils {

    /**
     * 实体bean 转换 map
     * 不转换的内容的filter中过滤
     *
     * @param fields
     * @param obj
     * @return map
     */
    public static Map<Object, Object> transToMap(Field[] fields, Object obj) {
        if (null == fields || null == obj) {
            return null;
        }

        Function<Field, Boolean> filter = (field) ->
                !"id".equals(field.getName())
                        || !"createdate".equals(field.getName())
                        || !"modifydate".equals(field.getName())
                        || !"syscodeid".equals(field.getName())
                        || !"organid".equals(field.getName());
        return Arrays.stream(fields)
                .filter(filter::apply)
                .map((Field field) -> {
                    try {
                        return new Pair(field.getName(), field.get(obj));
                    } catch (IllegalAccessException e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }
}
